﻿using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

public static class AssetUtils
{
	public static string[] FindAssetsByFilter( string filter )
	{
		return Directory.GetFiles( ".\\", filter, SearchOption.AllDirectories );
	}

	public static string[] FindFilesByFilter( string path, string filter )
	{
		return Directory.GetFiles( path, filter, SearchOption.AllDirectories );
	}

	public static string[] GetSubDirs( string path )
	{
		IEnumerable<string> list = from subdirectory in Directory.GetDirectories( path, "*", SearchOption.AllDirectories )
								   where Directory.GetDirectories( subdirectory ).Length == 0
								   select subdirectory;
		return list.ToArray();
	}

	public static void EnsureDirectoryExists( string dir )
	{
		if ( !Directory.Exists( dir ) )
			Directory.CreateDirectory( dir );
	}

	public static void SaveTextureToFile( Texture texture, string path )
	{
		Texture2D tex2D = texture as Texture2D;
		if ( tex2D == null )
			Debug.Log( "Функция понимает только Texture2D [texture.name: " + texture.name + "]" );

		string dirname = Path.GetDirectoryName( path );
		EnsureDirectoryExists( dirname );

		byte[] bytes = tex2D.EncodeToPNG();
		FileStream file = File.Open( path, FileMode.Create );
		BinaryWriter binary = new BinaryWriter( file );
		binary.Write( bytes );
		file.Close();
	}

#if UNITY_EDITOR

	public static Texture LoadTexture( string path )
	{
		if ( !File.Exists( path ) )
		{
			//Debug.LogError( "Нет такого файла\n" + path );
			return null;
		}
		return ( Texture ) AssetDatabase.LoadAssetAtPath( path, typeof( Texture ) );
	}

	public static void CreateAsset( Object asset, string path )
	{
		string dirname = Path.GetDirectoryName( path );
		EnsureDirectoryExists( dirname );
		AssetDatabase.CreateAsset( asset, path );
	}

	public static void CreatePrefab( GameObject go, string path )
	{
		string dirname = Path.GetDirectoryName( path );
		EnsureDirectoryExists( dirname );
		ReplacePrefabOptions flags = ReplacePrefabOptions.ConnectToPrefab | ReplacePrefabOptions.ReplaceNameBased;
		PrefabUtility.CreatePrefab( path, go, flags );
	}

#endif
}
